package dto;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Part;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import com.sun.mail.iap.Protocol;
import com.sun.mail.imap.IMAPFolder;

import vo.boardVO;
import vo.mailVO;
import db.MySql;

public class mailDTO {
	String m_id = "";
	
	int listSize = 10;
	int blockSize = 10;
	int totSize = 0;
	int totPage = 0;
	int totBlock = 0;
	int nowPage = 1;
	int nowBlock = 1;
	int startNo = 0;
	int endNo = 0;
	int startPage = 0;
	int endPage = 0;
	
	String protocol = "imap";
	mailVO vo = null;
	Connection conn = null;	

	public mailDTO() {
		conn = new MySql().getConn();
	}

	public mailDTO(mailVO vo) {
		this.vo = vo;
		this.nowPage = vo.getNowPage();
		this.nowBlock = vo.getNowBlock();
		conn = new MySql().getConn();
	}
		
	public mailVO emailInfo(mailVO vo){ // 1. 이메일 접속 정보를 구함. 
		this.vo = vo;
		
		String sql = "select e.e_name, e.e_email, e.e_email_pwd "
				+ "	from semyadmin.employees e join semyadmin.messenger m "
				+ " on m.e_number = e.e_number "
				+ " where m.m_id = ? ";
		
		try{
			PreparedStatement pst = conn.prepareStatement(sql);
			pst.setString(1, vo.getM_id());
			ResultSet rs = pst.executeQuery();
			rs.beforeFirst();
			while (rs.next()) {
				this.vo.setM_id(vo.getM_id());
				this.vo.setE_name(rs.getString("e.e_name"));
				this.vo.setEmail_address(rs.getString("e.e_email"));
				this.vo.setEmail_pwd(rs.getString("e.e_email_pwd"));
			}
			rs.close();
			pst.close();
			conn.close();
		}catch(Exception e){
			e.printStackTrace();
		}
		return this.vo;
	}
		
	public boolean SendSmtp(mailVO vo){		// 2. 메일 발송. 
		this.vo = vo;
		boolean b = false;     
		
	// host와 port 설정
		String e_name = vo.getE_name();
		final String address = vo.getEmail_sender();
		final String password = vo.getEmail_pwd();
		String receiver = vo.getEmail_receiver();
		String subject = vo.getEmail_subject();
		String contents = vo.getEmail_contents();
		//String filename = vo.getEmail_filename();
		String host = "";
		int port = 465;
		
		String [] a = address.split("@");
		
		if(a[1].equals("naver.com")){
			host = "smtp.naver.com";
		}else if(a[1].equals("gmail.com")){
			host = "smtp.gmail.com";
		}else if(a[1].equals("hanmail.net") || a[1].equals("daum.net")){
			host = "smtp.daum.net";						
		}else if(a[1].equals("nate.com")){
			host = "smtp.mail.nate.com";	
		}    
		System.out.println(a[1]);
		
		
	// 메일 보내기 (ssl 이용)
	        
		try {
			Properties props = System.getProperties();

			props.put("mail.smtp.host", host);
			props.put("mail.smtp.port", port);
			props.put("mail.smtp.auth", "true");
			props.put("mail.smtp.ssl.enable", "true");
			props.put("mail.smtp.ssl.trust", host);

			Session session = Session.getInstance(props, new javax.mail.Authenticator() {
				String un = address;
				String pw = password;

				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(un, pw);
				}
			});
			
			session.setDebug(true); // for debug

			Message msg = new MimeMessage(session);
			msg.setFrom(new InternetAddress(address)); // 에러나는 부분 
			msg.setRecipient(Message.RecipientType.TO, new InternetAddress(receiver));
			msg.setSubject(subject);
			msg.setSentDate(new Date());

			/*// 파일 첨부시에는 BodyPart를 사용
			// 

			// 파일첨부 
			if(filename != null || filename != ""){
			Multipart multipart = new MimeMultipart(); // 파일첨부를 위한 Multipart
			BodyPart bodyPart = new MimeBodyPart(); // BodyPart를 생성
			bodyPart.setText(contents);
			multipart.addBodyPart(bodyPart); 				// 1. Multipart에 contentsPart를 붙인다.
			DataSource source = new FileDataSource(filename); // 2. 파일을 첨부한다.
			bodyPart.setDataHandler(new DataHandler(source));
			bodyPart.setFileName(filename);
			msg.setContent(multipart);						// 이메일 메시지의 내용에 Multipart를 붙인다.
			}else{
			}*/
			msg.setText(contents);			
			Transport.send(msg);			
			b = true;
		}

		catch (Exception e) {
			e.printStackTrace();
		}
		return b;
	}
	
	public Properties getServerProperties(mailVO vo){	// 3. properties 설정 
		this.vo = vo;
		boolean b = false;     
		
	// host와 port 설정
		String e_name = vo.getE_name();
		final String address = vo.getEmail_address();
		final String password = vo.getEmail_pwd();
		String protocol ="imap";
		String host = "";
		int port = 993;
		
		String [] a = address.split("@");
		
		if(a[1].equals("naver.com")){
			host = "imap.naver.com";
		}else if(a[1].equals("gmail.com")){
			host = "imap.gmail.com";
		}else if(a[1].equals("hanmail.net") || a[1].equals("daum.net")){
			host = "imap.daum.net";						
		}else if(a[1].equals("nate.com")){
			host = "imap.nate.com";	
		}    
		
	
	// 메일 보내기 (ssl 이용)
	    
		Properties properties = new Properties();
		
        properties.put(String.format("mail.%s.host", protocol), host); // server setting
        properties.put(String.format("mail.%s.port", protocol), port);        
        properties.setProperty(String.format("mail.%s.socketFactory.class", protocol),
        									"javax.net.ssl.SSLSocketFactory"); // SSL setting
        properties.setProperty(String.format("mail.%s.socketFactory.fallback", protocol),"false"); 
        properties.setProperty(String.format("mail.%s.socketFactory.port", protocol), String.valueOf(port));
		       
        return properties;
	}
	
	
	
	public void page(int a){		// 4. 페이지 설정 
 
	    try {
    		
        	totSize = a;
            
			totPage = (int) Math.ceil(totSize * 1.0 / listSize);
			totBlock = (int) Math.ceil(totPage * 1.0 / blockSize);
			nowBlock = (int) Math.ceil(nowPage * 1.0 / blockSize);

			endPage = nowBlock * blockSize;
			startPage = endPage - blockSize + 1;

			endNo = nowPage * listSize;
			startNo = endNo - listSize + 1;

			if (endPage > totPage)
				endPage = totPage;
			if (endNo > totSize)
				totSize = endNo;
			
	    }catch(Exception e ){
	    	
	    }
	    
	}
	
    private String parseAddresses(Address[] address) {
        String listAddress = "";
 
        if (address != null) {
            for (int i = 0; i < address.length; i++) {
                listAddress += address[i].toString() + ", ";
            }
        }
        if (listAddress.length() > 1) {
            listAddress = listAddress.substring(0, listAddress.length() - 2);
        }
 
        return listAddress;
    }
	
    
    
    public ArrayList<mailVO> list(mailVO vo) { // list 처리 + 검색
		ArrayList<mailVO> al = new ArrayList<mailVO>();
		Properties properties = getServerProperties(vo);
	    Session session = Session.getDefaultInstance(properties);
	    
	    final String address = vo.getEmail_address();
		final String password = vo.getEmail_pwd();	
	 
	    try {
	    	Store store = session.getStore(protocol);
            store.connect(address, password);
             
            IMAPFolder f = (IMAPFolder) store.getFolder(vo.getEmail_list());
        	if(!f.isOpen()) f.open(Folder.READ_WRITE);
        		Message[] m = f.getMessages();
	        	int a =	f.getMessageCount();	
	        	page(a);
	        	System.out.println("m의 길이  : " + m.length);
	        	System.out.println("적용해야하는 값  : " + (m.length-1));
	        	
	        	int max_size = (m.length)-((vo.getNowPage()-1)*this.listSize);
	        	
	        	int min_size = max_size - this.listSize;
	        	if(min_size <= 0){
	        		min_size = 0;
	        	}
	        	System.out.println("max_size 값  : " + max_size);
	        	System.out.println("min_size 값  : " + min_size);
	        	
        	for (int i=min_size; i < max_size;i++) {
        	Message ms =  m[i];	
            String from = ((InternetAddress)((Address)(ms.getFrom()[0]))).getAddress();
            String subject = ms.getSubject();
            String toList = ((InternetAddress)((Address)(ms.getAllRecipients()[0]))).getAddress();
            String sentDate = ms.getSentDate().toLocaleString();

            String contentType = ms.getContentType();
            String messageContent = "";

            if (contentType.contains("text/plain") || contentType.contains("text/html")) {
                try {
                    Object content = ms.getContent();
                    if (content != null) {
                    	messageContent = content.toString();
                    }
                } catch (Exception ex) {
                    messageContent = "[Error downloading content]";
                    ex.printStackTrace();
                }
            }
            
            mailVO v = new mailVO();
            v.setEmail_number(i);
        	v.setEmail_sender(from);
            v.setEmail_receiver(toList);
        	v.setEmail_list(vo.getEmail_list());
        	v.setEmail_subject(subject);
        	v.setEmail_contents(messageContent);
        	v.setEmail_date(sentDate);
        	v.setEmail_size(String.valueOf(ms.getSize()).substring(1, 4)+"kb");  
        	al.add(v);        	
        	
        	}		
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return al;
	}
    
//    public mailVO View(mailVO vo) { 	// view : 선택한 글 보기 
//		mailVO v = new mailVO();
//
//		Properties properties = getServerProperties(v);
//	    Session session = Session.getDefaultInstance(properties);
//	    final String address = vo.getEmail_address();
//		final String password = vo.getEmail_pwd();	
//	 
//	    try {
//	    	Store store = session.getStore(protocol);
//            store.connect(address, password);
// 
//            Folder folderInbox = store.getFolder("INBOX");
//            folderInbox.open(Folder.READ_ONLY);
// 
//            IMAPFolder f = (IMAPFolder) store.getFolder(vo.getEmail_list());
//        	if(!f.isOpen()) f.open(Folder.READ_WRITE);
//        		Message[] m = f.getMessages();
//        		
//        	for (int i=0; i < m.length;i++) {
//        	Message ms =  m[i];	
//            Address[] fromAddress = ms.getFrom();
//            String from = fromAddress[0].toString();
//            String subject = ms.getSubject();
//            String toList = parseAddresses(ms.getRecipients(RecipientType.TO));
//            String ccList = parseAddresses(ms.getRecipients(RecipientType.CC));
//            String sentDate = ms.getSentDate().toString();
//            
//
//            String contentType = ms.getContentType();
//            String messageContent = "";
//
//            if (contentType.contains("text/plain") || contentType.contains("text/html")) {
//                try {
//                    Object content = ms.getContent();
//                    if (content != null) {
//                    	messageContent = content.toString();
//                    }
//                } catch (Exception ex) {
//                    messageContent = "[Error downloading content]";
//                    ex.printStackTrace();
//                }
//            }
//
//            // print out details of each message
//        	
//            v.setEmail_number(i);
//        	v.setEmail_sender(from);
//            v.setEmail_receiver(toList);
//        	v.setEmail_list(vo.getEmail_list());
//        	v.setEmail_subject(subject);
//        	v.setEmail_contents(messageContent);
//        	v.setEmail_date(sentDate);
//        	v.setEmail_size(String.valueOf(ms.getSize()));
//        	
//        	f.close(false);
//        	store.close();
//        	}
//		} catch (Exception e) {
//
//		}
//		return v;
//	}
    

    public boolean delete(mailVO vo){
    	boolean b = false;

    	return b;
    }
    
    
	public mailVO getVo() {
		return vo;
	}

	public void setVo(mailVO vo) {
		this.vo = vo;
		
	}

	public Connection getConn() {
		return conn;
	}

	public void setConn(Connection conn) {
		this.conn = conn;
	}

	public String getM_id() {
		return m_id;
	}

	public void setM_id(String m_id) {
		this.m_id = m_id;
	}

	public int getListSize() {
		return listSize;
	}

	public void setListSize(int listSize) {
		this.listSize = listSize;
	}

	public int getBlockSize() {
		return blockSize;
	}

	public void setBlockSize(int blockSize) {
		this.blockSize = blockSize;
	}

	public int getTotSize() {
		return totSize;
	}

	public void setTotSize(int totSize) {
		this.totSize = totSize;
	}

	public int getTotPage() {
		return totPage;
	}

	public void setTotPage(int totPage) {
		this.totPage = totPage;
	}

	public int getTotBlock() {
		return totBlock;
	}

	public void setTotBlock(int totBlock) {
		this.totBlock = totBlock;
	}

	public int getNowPage() {
		return nowPage;
	}

	public void setNowPage(int nowPage) {
		this.nowPage = nowPage;
	}

	public int getNowBlock() {
		return nowBlock;
	}

	public void setNowBlock(int nowBlock) {
		this.nowBlock = nowBlock;
	}

	public int getStartNo() {
		return startNo;
	}

	public void setStartNo(int startNo) {
		this.startNo = startNo;
	}

	public int getEndNo() {
		return endNo;
	}

	public void setEndNo(int endNo) {
		this.endNo = endNo;
	}

	public int getStartPage() {
		return startPage;
	}

	public void setStartPage(int startPage) {
		this.startPage = startPage;
	}

	public int getEndPage() {
		return endPage;
	}

	public void setEndPage(int endPage) {
		this.endPage = endPage;
	}
 
	
}
	
